﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculatorFlexibe.Interfaces;

namespace CalculatorFlexibe
{
    class ExpressionIsValid
    {
        private IOperation[] operationsArray;
        private INullPriorityOperation nullOperation;

        public ExpressionIsValid(IUploader uploader, INullPriorityOperation nullOperation)
        {
            operationsArray = uploader.UploadOperations(null , null);
            this.nullOperation = nullOperation;
        }
        public bool IsAllSymbolsCorrect(string str)
        {
            Array.ForEach(operationsArray, op => str = str.Replace(op.operation, ","));
            str = str.Replace(nullOperation.leftBoundary, ",");
            str = str.Replace(nullOperation.rightBoundary, ",");
            for (int i = 0; i < str.Length; i++)
            {
                if (!Char.IsDigit(str[i]) && str[i] != ',')
                    return false;
            }
            return true;
        }
        public bool Boundaries(string str)
        {
            int count = 0;
            str = str.Replace(nullOperation.leftBoundary, "(");
            str = str.Replace(nullOperation.rightBoundary, ")");
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == '(') count++;
                else if (str[i] == ')') count--;
                if (count < 0) return false;
            }
            return count == 0;
        }
        public bool IsValid(string str)
        {
            return IsAllSymbolsCorrect(str) && Boundaries(str);
        }
    }
}
